package com.qiongqi.datadir.handler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

import static com.qiongqi.datadir.utils.json.JsonSerializer.OBJECT_MAPPER;

/**
 * Redis 使用 Jackson 进行 JSON 序列化
 *
 * @author ruoyi (modified by Qwen)
 */
public class JacksonJsonRedisSerializer<T> implements RedisSerializer<T> {

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private final Class<T> clazz;

    public JacksonJsonRedisSerializer(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        try {
            String json = OBJECT_MAPPER.writeValueAsString(t);
            return json.getBytes(DEFAULT_CHARSET);
        } catch (JsonProcessingException e) {
            throw new SerializationException("Could not serialize object of class: " + clazz.getName(), e);
        }
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        try {
            String json = new String(bytes, DEFAULT_CHARSET);
            JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructType(clazz);
            return OBJECT_MAPPER.readValue(json, javaType);
        } catch (Exception e) {
            throw new SerializationException("Could not deserialize object of class: " + clazz.getName(), e);
        }
    }
}